#include "cgic.h"
#include <glib.h>
#include "msgUtils.h"

int cgiMain()
{
  // 1 获取gatewayIp和location
  char gatewayIp[256];
  cgiFormString("gatewayIp", gatewayIp, 256);
  char location[256];
  cgiFormString("location", location, 256);

  // 2写入devInfo.ini  [config] gatewayIp  location
  // 2.1 获取要保存文件路径
  GKeyFile *configKeyFile = g_key_file_new();

  if (!g_key_file_load_from_file(configKeyFile, "./config.ini", G_KEY_FILE_NONE, NULL))
  {
    g_warning("load config.ini error!");
    return -1;
  }
  gchar *deviceInfoPath = g_key_file_get_string(configKeyFile, "config", "deviceInfoPath", NULL);
  gchar *pathName = g_key_file_get_string(configKeyFile, "config", "pathName", NULL);
  g_key_file_free(configKeyFile);

  // 2.2 把信息写到那个文件中
  GKeyFile *deviceInfoFile = g_key_file_new();
  g_key_file_set_string(deviceInfoFile, "config", "gatewayIp", gatewayIp);
  g_key_file_set_string(deviceInfoFile, "config", "location", location);
  // 把设置的值保持到某个文件中
  g_key_file_save_to_file(deviceInfoFile, deviceInfoPath, NULL);
  g_key_file_free(deviceInfoFile);

  // 3 发一个消息通知heartprocess这个进程有新的配置
  int msgQueueId = obtain_msg_queue(pathName, ADS_BOA_MAIN_ID);
  if (msgQueueId == -1)
  {
    return -1;
  }
  Msg msg = {
      .type = 100,
      .content = "helloworld"};

  int retVal = msgsnd(msgQueueId, (const void *)&msg, strlen(msg.content) + 1, 0);
  if (retVal == -1)
  {
    return -1;
  }

  // 4 响应一个配置成功返回给界面
  // 告诉浏览器，是一个html文档
  cgiHeaderContentType("text/html");
  // 输出到客户端浏览器
  fprintf(cgiOut, "<html><head><title>hello</title></head><body>");
  fprintf(cgiOut, "sucess!");
  fprintf(cgiOut, "</body></html>");

  return 0;
}